﻿using System;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Helpers;
using Ayatta.Common;
using Ayatta.Common.Extension;
using Ayatta.Contract.Config;
using Ayatta.Contract.Domain;
using Enyim.Caching;
using Ayatta.Contract;
using System.Web.Mvc;
using Web.Core.Controllers;
using Web.Core.Components;
using System.Collections.Generic;
using Web.Core.EventArgs;
using Web.Core.Extensions;
using Web.Core.OAuths;
using Web.Core.Security;

namespace Web.Passport.Controllers
{
    public class SignUpController : BaseController
    {
        private const string SignUpCaptchaKey = "signup";
        public SignUpController(Lazy<IInfrastructureService> infrastructure, Lazy<IPassportService> passport, Lazy<IAccountService> account, Lazy<IStoreService> store, Lazy<ITradeService> trade, Lazy<IPlayService> play, Lazy<IMiscService> misc, Lazy<IExtraService> extra, IMemcachedClient memcachedClient)
            : base(infrastructure, passport, account, store, trade, play, misc, extra, memcachedClient)
        {
        }

        #region 使用邮箱注册
        /// <summary>
        /// 使用邮箱进行注册需要验证邮箱是否有效
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 使用邮箱进行注册需要验证邮箱是否有效
        /// </summary>
        /// <param name="email">邮箱地址</param>
        /// <param name="password">登录密码</param>
        /// <param name="captcha">验证码</param>
        /// <param name="traceCode">跟踪代码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(string email, string password, string captcha, string traceCode)
        {
            var result = new MagicKit<string>();
            if (!email.IsEmail())
            {
                result.Message = "请输入正确的电子邮箱地址！";
                return Json(result);
            }
            if (!password.IsPassword())
            {
                result.Message = "6-12位，至少两个字母、两个数字、一个特殊字符！";
                return Json(result);
            }
            if (!CaptchaValidateInternal(SignUpCaptchaKey, captcha))
            {
                result.Message = "请输入正确的验证码！";
                return Json(result);
            }
            var exist = Passport.Value.UserExist(email);
            if (!exist.Status)
            {
                var pre = new PreUser();
                var auth = new AuthEmail();

                var id = Guid.NewGuid().ToString().ToUpper();

                pre.Id = id;
                pre.Origin = 1;
                pre.UserName = email;
                pre.Password = password.HashPassword();
                pre.UserAgent = GetUserAgent();
                pre.Browser = GetBrowser();
                pre.IpAddress = GetIpAddress();
                pre.UrlReferrer = GetUrlReferrer();
                pre.CreatedBy = "";
                pre.CreatedOn = DateTime.Now;
                pre.TraceCode = traceCode;

                auth.Id = id;
                auth.UserId = 0;
                auth.Group = 0;
                auth.Email = email;
                auth.Status = false;
                auth.CreatedBy = "sys";
                auth.CreatedOn = DateTime.Now;

                Passport.Value.PreUserCreate(pre);
                Extra.Value.AuthEmailCreate(auth);

                result.Status = true;
                result.Data = id;
            }
            else
            {
                result.Message = "该邮箱已被使用，请换一个！";
            }
            return Json(result);
        }

        /// <summary>
        /// 验证邮箱
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public ActionResult Validate(string param)
        {
            var time = DateTime.Now;
            var model = new MagicKit<string>();
            if (!string.IsNullOrEmpty(param))
            {
                var pre = Passport.Value.PreUserGet(param);
                if (pre == null)
                {
                    model.Message = "链接无效或已过期！";
                }
                else
                {
                    var exist = Passport.Value.UserExist(pre.UserName);
                    if (!exist.Status)
                    {
                        var user = new User();
                        var profile = new UserProfile();
                        var extra = new UserExtra();

                        user.Guid = pre.Id;
                        user.Name = pre.UserName;
                        user.Nickname = string.Empty;
                        user.Password = (pre.Password + PasswordSalt).HashPassword();
                        user.PayPassword = string.Empty;
                        user.Role = UserRole.Buyer;
                        user.Level = UserLevel.None;
                        user.Limit = UserLimit.None;
                        user.Permit = UserPermit.None;
                        user.Email = pre.UserName;
                        user.Mobile = string.Empty;
                        user.Avatar = false;
                        user.Status = UserStatus.Normal;
                        user.Authenticated = false;
                        user.AuthenticatedOn = null;
                        user.CreatedBy = string.Empty;
                        user.CreatedOn = time;

                        profile.Code = string.Empty;
                        profile.Name = string.Empty;
                        profile.Gender = Gender.Secrect;
                        profile.Marital = Marital.Secrect;
                        profile.Birthday = null;
                        profile.Phone = string.Empty;
                        profile.Mobile = string.Empty;
                        profile.AreaId = string.Empty;
                        profile.SignUpIp = GetIpAddress();
                        profile.SignUpBy = 1;
                        profile.TraceCode = pre.TraceCode;
                        profile.LastSignInIp = GetIpAddress();
                        profile.LastSignInOn = time;

                        extra.Game = string.Empty;
                        extra.LastServerId = 0;

                        user.Profile = profile;
                        user.Extra = extra;

                        var id = Passport.Value.UserCreate(user);
                        if (id > 0)
                        {
                            model.Status = true;
                            model.Data = id.ToString();
                            Extra.Value.AuthEmailStatusUpdate(param);
                            SetAuthCookie(user.Name, false, new Identity(id,user.Guid,user.Nickname, user.Role));
                        }
                        else
                        {
                            model.Message = "注册失败，请稍后再试！";
                        }
                    }
                    else
                    {
                        model.Message = "该帐号已激活！";
                    }
                }
            }
            else
            {
                model.Message = "参数不正确！";
            }
            return View(model);
        }
        #endregion

        #region 使用手机号注册

        /// <summary>
        /// 使用手机号码注册 需要验证手机号码是否有效
        /// </summary>
        /// <returns></returns>
        public ActionResult Mobile()
        {
            return View();
        }

        /// <summary>
        /// 使用手机号码注册
        /// </summary>
        /// <param name="mobile">手机号</param>
        /// <param name="password">登录密码</param>
        /// <param name="authId">短信验证Id</param>
        /// <param name="authCode">短信验证码</param>
        /// <param name="traceCode">跟踪代码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Mobile(string mobile, string password, string authId, string authCode, string traceCode)
        {
            var time = DateTime.Now;
            var result = new MagicKit<string>();
            if (!mobile.IsMobile())
            {
                result.Message = "请输入正确的手机号码！";
                return Json(result);
            }
            if (!password.IsPassword())
            {
                result.Message = "6-12位，至少两个字母、两个数字、一个特殊字符！";
                return Json(result);
            }
            var auth = Extra.Value.AuthSmsGet(authId, mobile, 0, authCode);
            if (auth == null || auth.Status || mobile != auth.Mobile)
            {
                result.Message = "短信验证码不正确或已过期！";
                return Json(result);
            }
            var exist = Passport.Value.UserExist(mobile);
            if (!exist.Status)
            {
                var user = new User();
                var profile = new UserProfile();
                var extra = new UserExtra();

                user.Guid = auth.Id;
                user.Name = mobile;
                user.Nickname = string.Empty;
                user.Password = (password.HashPassword() + PasswordSalt).HashPassword();
                user.PayPassword = string.Empty;
                user.Role = UserRole.Buyer;
                user.Level = UserLevel.None;
                user.Limit = UserLimit.None;
                user.Permit = UserPermit.None;
                user.Email = string.Empty;
                user.Mobile = mobile;
                user.Avatar = false;
                user.Status = UserStatus.Normal;
                user.Authenticated = false;
                user.AuthenticatedOn = null;
                user.CreatedBy = string.Empty;
                user.CreatedOn = time;

                profile.Code = string.Empty;
                profile.Name = string.Empty;
                profile.Gender = Gender.Secrect;
                profile.Marital = Marital.Secrect;
                profile.Birthday = null;
                profile.Phone = string.Empty;
                profile.Mobile = string.Empty;
                profile.AreaId = string.Empty;
                profile.SignUpIp = GetIpAddress();
                profile.SignUpBy = 1;
                profile.TraceCode = traceCode;
                profile.LastSignInIp = GetIpAddress();
                profile.LastSignInOn = time;

                extra.Game = string.Empty;
                extra.LastServerId = 0;

                user.Profile = profile;
                user.Extra = extra;

                var id = Passport.Value.UserCreate(user);
                if (id > 0)
                {
                    result.Status = true;
                    result.Data = id.ToString();
                    var identity = new Identity(user.Id, user.Guid, user.Nickname, user.Role);
                    SetAuthCookie(user.Name, false, identity);
                }
                else
                {
                    result.Message = "注册失败，请稍后再试！";
                }
            }
            else
            {
                result.Message = "该手机号码已被使用，请换一个！";
            }
            return Json(result);
        }

        #endregion
    }
}
